import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from '../Users.css';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import * as customFun from '../../../services/AccountDivi';
const daoName = "IndiYJ";
const ButtonGroup = Button.Group;
const columns = [
    { title: '产品编号', width: 150, sorter: true, dataIndex: "PUNO", key: 'PUNO', dispaly: true, filter: true, export: true },
    { title: '所属产品', width: 180, sorter: true, dataIndex: 'PUNM', key: 'PUNM', dispaly: true, filter: true, export: true },
    { title: '身份证号', width: 180, sorter: true, dataIndex: "IDNO", key: 'IDNO', dispaly: true, filter: true, export: true },
    { title: '客户名称', width: 120, sorter: true, dataIndex: "CUNM", key: 'CUNM', dispaly: true, filter: true, export: true },
    { title: '卡号', width: 160, sorter: true, dataIndex: "CDNO", key: 'CDNO', dispaly: true, filter: true, export: true },
    { title: '起息日', width: 110, sorter: true, key: 'BGDT', caption: "BGDT", dispaly: true, filter: true, render: data => datetime.format(data.BGDT, "yyyy-MM-dd") },
    { title: '到期日', width: 110, sorter: true, key: 'FNDT', caption: "FNDT", dispaly: true, filter: true, render: data => datetime.format(data.FNDT, "yyyy-MM-dd") },
    { title: '余额', width: 120, sorter: true, dataIndex: "ACBL", key: 'ACBL', dispaly: true, filter: true, export: true },
    { title: '工号', width: 120, sorter: true, dataIndex: "SysUserID", key: 'SysUserID', dispaly: true, filter: true, export: true },
];
let controls = [
    { name: 'PUNO', type: 'text', label: '产品编号', required: true, grid: 12 / 24 },
    { name: 'PUNM', type: 'text', label: '所属产品', required: true, grid: 12 / 24 },
    { name: 'IDNO', type: 'text', label: '身份证号', required: true, grid: 12 / 24 },
    { name: 'CUNM', type: 'text', label: '客户名称', required: true, grid: 12 / 24 },
    { name: 'CDNO', type: 'text', label: '卡号', required: true, grid: 12 / 24 },
    { name: 'BGDT', required: true, type: 'date', dataType: "date", label: '起息日', grid: 12 / 24 },
    { name: 'FNDT', required: true, type: 'date', dataType: "date", label: '到期日', grid: 12 / 24 },
    { name: 'ACBL', type: "number", label: '余额', required: true, grid: 12 / 24 },
    { name: 'SysUserID', type: 'text', label: '工号', required: true, grid: 12 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class IndiYJForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            searchData: {},
            dataList: []
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let sort = {
            field: 'BGDT',
            order: 'descend'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    edidOkHandler() {
        const form = this.refs.OrganForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                let t = `${daoName}/create`
                const { keyName, record } = this.props;
                let msg = "数据添加成功！"
                if (record[keyName]) {
                    values[keyName] = record[keyName];
                    t = `${daoName}/patch`
                    msg = "数据修改成功！"
                }
                controls.map((c, i) => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        const date = !values[c.name] ? null : new Date(values[c.name])
                        values[c.name] = date ? new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0) : null
                    } else if (c.dataType === "month") {
                        const date = !values[c.name] ? null : new Date(values[c.name])
                        let month = date.getMonth() + 1
                        if (month < 10) {
                            month = "0" + month
                        }
                        values[c.name] = date ? date.getFullYear() + "-" + month : null
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                this.state.dataChange = true;
                this.props.dispatch({
                    type: t,
                    payload: { daoName, values },
                })
            }
        });
    };

    searchHandle(data) {
        this.state.searchData = data
    };
    onSelectChangeHandler(newList) {
        this.setState({ dataList: newList })
    }
    alterGh() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要修改的数据行！', 5);
            return;
        }
        const searchData = this.state.searchData
        const uid = Number(searchData.ID)
        const dataList = this.state.dataList[0]
        const acid = Number(dataList.ID)
        
        Modal.confirm({
            title: '提示',
            content: `你确认要修改客户经理工号吗`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                customFun.SaveGh({ acid, uid }
                ).then(function (data) {
                    if (data === 'ok') {
                        message.success("修改工号成功!")
                        // 清空填写表单的内容
                        const form = this.refs.OrganForm.getForm();
                        form.resetFields();
                        this.componentDidMount()
                    } else {
                        message.error("修改工号失败!")
                    }
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
            }
        });

    }
    render() {
        let { record, permID, popedomTypes, patp } = this.props
        const pTypes = popedomTypes[permID]
        const controlsFilter = [
            { name: 'YG', required: true, type: 'search', label: '客户经理', grid: 5 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this), permID: permID } },
            {
                name: 'BT', required: false, type: 'button-group',
                data: [
                    { value: '1', label: '修改', onClick: this.alterGh.bind(this) }], grid: 4 / 24
            },
        ];
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        <EditFrom ref="OrganForm" daoName={daoName} controls={controlsFilter} record={record} />
                    </div>
                    <DataTable ref="OrganTable" daoName={daoName} columns={columns} controls={controls} permID={permID} onSelectChange={this.onSelectChangeHandler.bind(this)} />
                </div>
            </div>
        )
    }
}
function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record,
    }
}
IndiYJForm = connect(mapStateToProps)(IndiYJForm)
export default IndiYJForm;

let render = (props) => React.createElement(IndiYJForm, props);
let f = new Factory()
f.set("IndiYJForm", render)
